//
//  ACLiveRoomManager.m
//  ACLiteAVUISDK-ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/4/12.
//

#import "ACLiveRoomManager.h"

@implementation ACLiveRoomManager

// 创建路演
+(void)requestCreateRoadShowWitchInfo:(NSDictionary *)dicInfo requestCallback:(RequestHandler)requestCallback{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/show"];
    [[ACNetWorkTool shareRequestManager] post:url params:dicInfo success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        if (requestCallback) {
            requestCallback(0,@"successfully");
        }
    } failure:^(NSError * _Nonnull error) {
        DDLogInfo(@"%@",error);
        if (requestCallback) {
            requestCallback(-1,@"failed");
        }
    }];
}
// 上传图片
+(void)uploadImageWithImageData:(NSData *)imageData success:(void (^)(id responseObject))success{
    NSDictionary *params = @{@"file":imageData};
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/common/upload"];
    [[ACNetWorkTool shareRequestManager] post:url contentType:@"form-data" params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        DDLogInfo(@"%@",error);
    }];
}

// 修改未开始路演的信息
+(void)requestModiftLiveInfoWithLiveID:(NSString *)liveID Info:(NSDictionary *)dicInfo requestCallback:(RequestHandler)requestCallback{
    
}

// 获取自己创建的路演列表
+(void)requestMyRoadShowWithPage:(NSString *)page success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/show"];
    NSDictionary *params = @{@"page_size":@"20",@"page":page};
    [[ACNetWorkTool shareRequestManager] get:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        DDLogInfo(@"%@",error);
        failure(error);
    }];
}

// 开始或者结束路演的状态
+(void)requestModityWithLiveID:(NSString *)liveID Status:(NSString *)status requestCallback:(RequestHandler)requestCallback{
    NSString *type = [status intValue] == 1 ? @"begin":@"end";
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/begin_end"];
    NSDictionary *params = @{@"id":@([liveID intValue]),@"type":type};
    [[ACNetWorkTool shareRequestManager] post:url params: params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        requestCallback(-1,@"failed");
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

// 判断是否可以直接进入路演
+(void)requestCheckAuthorityWithLiveID:(NSString *)liveID requestCallback:(RequestHandler)requestCallback{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/enter/",liveID];
    [[ACNetWorkTool shareRequestManager] post:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        BOOL can_enter = [[responseObject valueForKey:@"can_enter"] boolValue];
        BOOL need_password = [[responseObject valueForKey:@"need_password"] boolValue];
        if (can_enter) {
            if (need_password) {
                // 弹出 alertVC
                __block NSString *pwdStr = @"";
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"入场密码" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    DDLogInfo(@"%@",pwdStr);
                    [ACLiveRoomManager requestCheckWithliveID:liveID Password:pwdStr requestCallback:^(int code, NSString * _Nullable message) {
                        if (code == 0 ) {
                            requestCallback(0,@"successfully");
                        }else{
                            [SVProgressHUD showErrorWithStatus:@"密码错误"];
                        }
                    }];
                }];
                [alertVC addAction:cancelAction];
                [alertVC addAction:sureAction];
                [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                    textField.placeholder = @"输入密码";
                    textField.borderStyle = UITextBorderStyleNone;
                    textField.wgk_didEndEditingBlock = ^(UITextField *textField) {
                        pwdStr = textField.text;
                    };
                }];
                [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
            }else{
                requestCallback(0,@"successfully");
            }
        }else{
            NSString *message = [responseObject valueForKey:@"message"];
            [SVProgressHUD showInfoWithStatus:message];
        }
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络错误"];
        if (requestCallback) {
            requestCallback(-1,@"failed");
        }
    }];
}

// 预约观看他人路演
+(void)requestBookLiveWithLiveID:(NSString *)liveID requestCallback:(RequestHandler)requestCallback{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/book/",liveID];
    [[ACNetWorkTool shareRequestManager] post:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        if (requestCallback) {
            requestCallback(0,@"successfully");
        }
    } failure:^(NSError * _Nonnull error) {
        if (requestCallback) {
            requestCallback(-1,@"failed");
        }
    }];
}

// 获取自己预约的路演列表
+(void)requesrBookListWithPage:(NSString *)page success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/book"];
    NSDictionary *params = @{@"page_size":@"20",@"page":page};
    [[ACNetWorkTool shareRequestManager] get:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        DDLogInfo(@"%@",error);
        failure(error);
    }];
}

// 验证路演密码
+(void)requestCheckWithliveID:(NSString *)liveID Password:(NSString *)password requestCallback:(RequestHandler)requestCallback{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/password"];
    NSDictionary *params = @{@"password":password,@"id":liveID};
    [[ACNetWorkTool shareRequestManager] post:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        requestCallback(-1,@"failed");
    }];
}

// 获取路演的文件列表
+(void)requestFileListWithLiveID:(NSString *)liveID success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/files/",liveID];
    [[ACNetWorkTool shareRequestManager] get:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}
// 获取路演文件详情
+(void)requestFileInfoWithFileID:(NSString *)fileID success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/material/material/",fileID];
    [[ACNetWorkTool shareRequestManager] get:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}
// 获取首页路演直播列表
+(void)requestLiveListWithPage:(NSString *)page success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/show_all"];
    NSDictionary *params = @{@"page_size":@"20",@"page":page};
    [[ACNetWorkTool shareRequestManager] get:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}

// 发布对路演的反馈
+(void)requestFeedBackWithLiveID:(NSString *)liveID feedBackStatus:(int)feedBackStatus requestCallback:(RequestHandler)requestCallback{
    NSString *level = @"support";
    if (feedBackStatus == 2) {
        level = @"attention";
    }else if (feedBackStatus == 1){
        level = @"cautious";
    }
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/feedback"];
    NSDictionary *params = @{@"id":liveID,@"level":level};
    [[ACNetWorkTool shareRequestManager] post:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        int code = (int)error.code;
        requestCallback(code,@"failured");
    }];
}
// 获取某个路演的反馈详情
+(void)requestFeedBackInfoWithLiveID:(NSString *)liveID success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/feedback/",liveID];
    [[ACNetWorkTool shareRequestManager] get:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}
// 获取路演详情
+(void)requestLiveDetailWithLiveID:(NSString *)liveID success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/show/",liveID];
    [[ACNetWorkTool shareRequestManager] get:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}
// 发出提问申请
+(void)requestToAskWithLiveID:(NSString *)liveID requestCallback:(RequestHandler)requestCallback{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/ask/",liveID];
    [[ACNetWorkTool shareRequestManager] post:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        requestCallback(-1,@"failured");
    }];
}
// 判断是否可以发言
+(void)requsetAskStatusWithLiveID:(NSString *)liveID requestCallback:(RequestHandler)requestCallback{
    NSString *url = [NSString stringWithFormat:@"%@%@%@",HOSTURL,@"/api/v1/road/ask/",liveID];
    [[ACNetWorkTool shareRequestManager] get:url params:[NSDictionary dictionary] success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        requestCallback(-1,@"failured");
    }];
}
// 获取提问列表
+(void)requestAskListLiveID:(NSString *)liveID success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/road/question"];
    NSDictionary *params = @{@"room_id":liveID,@"page":@"1",@"page_size":@"50"};
    [[ACNetWorkTool shareRequestManager] get:url params:params success:^(id  _Nonnull responseObject) {
        DDLogInfo(@"%@",responseObject);
        success(responseObject);
    } failure:^(NSError * _Nonnull error) {
        failure(error);
    }];
}
// 开始白板推流
+(void)requestStartPublishWithLiveID:(NSString *)liveID boardSize:(CGSize)boardSize boardParams:(NSString *)boardParams requestCallback:(RequestHandler)requestCallback{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/tencent/push/begin"];
    NSString * paramStr = [ NSString stringWithFormat : @"room_id=%@" ,liveID];
    NSURLSession * mySession = [ NSURLSession sharedSession ];
    NSURL * fullURL = [NSURL URLWithString:url];
    NSMutableURLRequest * request = [ NSMutableURLRequest requestWithURL :fullURL cachePolicy : NSURLRequestUseProtocolCachePolicy timeoutInterval : 7.0 ];
    request. HTTPMethod = @"POST" ;
    [request addValue : @"application/x-www-form-urlencoded" forHTTPHeaderField : @"Content-Type" ];
    request. HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *token_user = [[ACUserProfileManager shareInstance] getToken];
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    if (![token_user isEqualToString:@""]) {
        NSString *token = [NSString stringWithFormat:@"Bearer %@",token_user];
        [dic setValue:token forKey:@"Authorization"];
        [dic enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {
            [request setValue:value forHTTPHeaderField:key];
        }];
    }
    NSURLSessionDataTask * task = [mySession dataTaskWithRequest :request completionHandler :^( NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          // 判断接口是否成功返回
        if (error) {// 接口访问失败
            DDLogInfo ( @"error:%@" ,error. localizedDescription );
            DDLogInfo ( @"%s" ,__func__);
            [SVProgressHUD showErrorWithStatus:@"白板推流失败"];
        }else{// 接口访问成功
            NSError * parseError1 = nil ;
            NSDictionary * dic = [ NSJSONSerialization JSONObjectWithData :data options : NSJSONReadingMutableContainers error :&parseError1];
            if (parseError1) {
                DDLogInfo ( @"JSON 解析错误 " );
                [SVProgressHUD showErrorWithStatus:@"白板推流失败"];
                return ;
            }
            DDLogInfo ( @"data:%@" , dic);
            if ([dic.allKeys containsObject:@"data"]) {
                
                NSDictionary *responseObject = [dic objectForKey : @"data"];
                NSString *task_ID = [responseObject objectForKey:@"task_id"];
                requestCallback(0,task_ID);
            }else{
                NSString *msg = [dic objectForKey:@"errors"];
                if ([msg containsString:@"already used in other whiteboard push task, task_id:"]) {
                    NSArray *array = [msg componentsSeparatedByString:@"task_id:"];
                    NSString *taskID = array.lastObject;
                    [ACLiveRoomManager requestEndPublishWithLiveID:liveID task_id:taskID requestCallback:^(int code, NSString * _Nullable message) {
                        [ACLiveRoomManager requestStartPublishWithLiveID:liveID boardSize:CGSizeMake(100, 100) boardParams:@"" requestCallback:requestCallback];
                    }];
                }else{
                    [SVProgressHUD showErrorWithStatus:msg];
                }
            }
        }
    }];
    [task resume ];
}
// 结束白板推流
+(void)requestEndPublishWithLiveID:(NSString *)liveID task_id:(NSString *)task_id requestCallback:(RequestHandler)requestCallback{
    NSString *url = [HOSTURL stringByAppendingString:@"/api/v1/tencent/push/end"];
    NSDictionary *params = @{@"room_id":liveID,@"task_id":task_id};
    [[ACNetWorkTool shareRequestManager] post:url params:params success:^(id  _Nonnull responseObject) {
        requestCallback(0,@"successfully");
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"停止推流失败，请稍后再试"];
    }];
}
@end

